import { useState, useEffect } from 'react'
import { Drawer } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { getMyChannels, selectTab } from '@/store/actions'

import Tabs from '@/components/Tabs'
import Icon from '@/components/Icon'
import Channels from './components/Channels'
import ArticleList from './components/ArticleList'

import styles from './index.module.scss'
// withRouter 是路由提供的高阶组件，用来让组件接收路由相关的信息
// 因此，该高阶的作用：就是复用 路由相关的状态逻辑
import { withRouter } from 'react-router'

const Home = props => {
  // console.log('Home', props)
  // 拿到dispatch
  const dispatch = useDispatch()
  // 拿 redux 中的频道数据
  const { channels, channelActiveIndex } = useSelector(state => state.home)
  // console.log(tabs)
  const [open, setOpen] = useState(false)

  // 进入页面时，获取频道数据
  useEffect(() => {
    dispatch(getMyChannels())
  }, [dispatch])

  // 关闭 channels
  const onClose = () => setOpen(false)

  // 切换 tab 时，更新 redux 中的状态
  const onTabChange = index => {
    dispatch(selectTab(index))
  }

  return (
    <div className={styles.root}>
      <Tabs
        activeKey={channelActiveIndex}
        onTabChange={onTabChange}
        tabs={channels}
      >
        {channels.map(item => (
          <ArticleList key={item.id} channelId={item.id} />
        ))}
      </Tabs>

      <div className="tabs-opration">
        {/* <Icon type="iconbtn_search" onClick={() => history.push('/search')} /> */}
        <Icon
          type="iconbtn_search"
          onClick={() => props.history.push('/search')}
        />
        <Icon type="iconbtn_channel" onClick={() => setOpen(true)} />
      </div>

      <Drawer
        className="channel-drawer"
        sidebar={channels.length > 0 ? <Channels onClose={onClose} /> : ''}
        open={open}
      >
        {''}
      </Drawer>
    </div>
  )
}

const HomeHOC = withRouter(Home)

export default HomeHOC
